package daybook.io.shell;

import daybook.exception.ApplicationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.script.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;

public class JsShell {
    private static final Logger LOG = LoggerFactory.getLogger(JsShell.class);
    private static final String PRELUDE = "prelude.js";
    private static final String ENGINE_NAME = "nashorn";
    private final ShellContext context;
    private final ScriptEngine engine = new ScriptEngineManager().getEngineByName(ENGINE_NAME);

    public JsShell(ShellContext context) {
        this.context = Objects.requireNonNull(context);
    }

    public void init() {
        LOG.trace(">>> init");
        LOG.debug("=== init: set bindings");
        final Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
        bindings.put("context", context);
        final Path prelude = Paths.get(ClassLoader.getSystemResource(PRELUDE).getPath());
        if (LOG.isDebugEnabled()) {
            LOG.debug("=== init: loading prelude {}", prelude.toAbsolutePath().normalize());
        }
        try {
            engine.eval(Files.newBufferedReader(prelude));
            LOG.debug("=== init: loaded prelude");
        } catch (IOException e) {
            LOG.debug("=== init: io error when loading prelude");
            throw new ApplicationException("io error when loading prelude", e);
        } catch (ScriptException e) {
            LOG.debug("=== init: error when evaluating prelude");
            throw new ApplicationException("error when evaluating prelude", e);
        }
        LOG.trace("<<< init");
    }

    public ShellContext getBook() {
        return context;
    }

    public ScriptEngine getEngine() {
        return engine;
    }

    public void repl() {
        LOG.trace(">>> repl");
        final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String line;
        try {
            System.out.print("> ");
            while ((line = reader.readLine()) != null) {
                LOG.trace("=== repl: line: {}", line);
                try {
                    final Object value = engine.eval(line);
                    if (value != null) {
                        System.out.println(value);
                    }
                } catch (ScriptException e) {
                    LOG.trace("=== repl: error when evaluating javascript " + line, e);
                    System.out.println(e.getMessage());
                }
                System.out.print("> ");
            }
        } catch (IOException e) {
            LOG.debug("=== repl: io error when reading from stdin", e);
            throw new ApplicationException(e);
        }
        LOG.trace("<<< repl");
    }
}
